<template>
    <el-row class="contain-box">
        <site-nav/>
        <div class="view-body">
            <el-row>
                <el-form>
                    <el-form-item>
                        <el-button @click="$router.go(-1)"><i class="el-icon-arrow-left el-icon--left"/>返回
                        </el-button>
                    </el-form-item>
                    <el-steps :active="active" finish-status="success">
                        <el-step title="选择模板"/>
                        <el-step title="设置参数"/>
                        <el-step title="选择用户"/>
                        <el-step title="发送确认"/>
                        <el-step title="发送结果"/>
                    </el-steps>
                    <el-form-item>
                    </el-form-item>
                    <el-form-item v-if="active === 0">
                        <el-select clearable filterable placeholder="请选择" v-model="currentTemplate"
                                   @change="changeTemplate" value-key="priTmplId">
                            <el-option v-for="item in templates" :key="item.priTmplId"
                                       :value="item" :label="item.title"/>
                        </el-select>
                    </el-form-item>
                    <template v-if="active === 1">
                        <el-form :model="values" :rules="formRules" ref="argForm" size="small">
                            <el-form-item v-for="(label, key) in args" :key="key" :label="'参数(' + key + '): ' + label" :prop="key" :required="true">
                                <el-input clearable v-model="values[key]"/>
                            </el-form-item>
                        </el-form>
                        <el-form-item>
                            <el-button @click="init"><i class="el-icon-arrow-left el-icon--left"/>上一步
                            </el-button>
                            <el-button @click="toSelectUserPage" type="primary">下一步<i class="el-icon-arrow-right el-icon--right"/>
                            </el-button>
                        </el-form-item>
                    </template>
                    <template v-if="active === 2">
                        <el-row>
                            <el-form class="inline-form" inline>
                                <el-form-item>
                                    <el-button @click="active = 1"><i class="el-icon-arrow-left el-icon--left"/>上一步
                                    </el-button>
                                </el-form-item>
                                <el-form-item label="openId">
                                    <el-input @clear="search" clearable placeholder="请输入openId"
                                              v-model="params.openId"/>
                                </el-form-item>
                                <el-form-item label="unionId">
                                    <el-input @clear="search" clearable placeholder="请输入unionId"
                                              v-model="params.unionId"/>
                                </el-form-item>
                                <el-form-item label="昵称">
                                    <el-input @clear="search" clearable placeholder="请输入昵称"
                                              v-model="params.nickNameLike"/>
                                </el-form-item>
                                <el-form-item label="标签">
                                    <el-select @change="search" clearable filterable placeholder="请选择" v-model="params.tagId">
                                        <el-option value="" label="不限"/>
                                        <el-option v-for="item in tags" :key="item.tagId"
                                                   :value="item.tagId" :label="item.tagName"/>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="激活">
                                    <el-select @change="search" clearable filterable placeholder="请选择" v-model="params.activated">
                                        <el-option value="" label="不限"/>
                                        <el-option :value="true" label="是"/>
                                        <el-option :value="false" label="否"/>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="注册时间">
                                    <el-date-picker
                                            v-model="registryTimes"
                                            type="datetimerange"
                                            range-separator="至"
                                            start-placeholder="开始时间"
                                            end-placeholder="结束时间"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            @change="search"
                                    />
                                </el-form-item>
                                <el-form-item label="最后登录时间">
                                    <el-date-picker
                                            v-model="lastLoginTimes"
                                            type="datetimerange"
                                            range-separator="至"
                                            start-placeholder="开始时间"
                                            end-placeholder="结束时间"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            @change="search"
                                    />
                                </el-form-item>
                                <el-form-item>
                                    <el-button @click="search" icon="el-icon-search" type="primary">搜索</el-button>
                                    <el-button @click="toConfirm(false)" type="primary"
                                               :disabled="selectNumber === 0">下一步
                                    </el-button>
                                    <el-button @click="toConfirm(true)" type="primary">选择全部用户
                                    </el-button>
                                </el-form-item>
                            </el-form>
                        </el-row>
                        <el-row>
                            <el-col>已选择：{{selectNumber}}名用户</el-col>
                        </el-row>
                        <el-row>
                            <el-col>
                                <el-table :data="users" border size="small"
                                          @select="selectUser"
                                          @select-all="selectUser"
                                          ref="userTable" current-row-key="openId"
                                >
                                    <el-table-column type="selection" width="55"/>
                                    <el-table-column align="center" label="openId" prop="openId"/>
                                    <el-table-column align="center" label="unionId" prop="unionId"/>
                                    <el-table-column align="center" label="昵称" prop="nickName"/>
                                    <el-table-column align="center" label="头像" width="80">
                                        <template slot-scope="scope">
                                            <el-avatar shape="square" :src="scope.row.avatarUrl"/>
                                        </template>
                                    </el-table-column>
                                    <el-table-column align="center" label="注册时间" width="90">
                                        <template slot-scope="scope">
                                            <p class="date-time">{{scope.row.registryTime | dateFormat}}</p>
                                            <p class="date-time">{{scope.row.registryTime | timeFormat}}</p>
                                        </template>
                                    </el-table-column>
                                    <el-table-column align="center" label="最后登录时间" width="100">
                                        <template slot-scope="scope">
                                            <p class="date-time">{{scope.row.lastLoginTime | dateFormat}}</p>
                                            <p class="date-time">{{scope.row.lastLoginTime | timeFormat}}</p>
                                        </template>
                                    </el-table-column>
                                    <el-table-column align="center" label="激活用户" width="80">
                                        <template slot-scope="scope">
                                            <commons-enable :value="scope.row.activated"/>
                                        </template>
                                    </el-table-column>
                                    <el-table-column align="center" label="标签">
                                        <template slot-scope="scope">
                                            <span class="tag" v-for="tag in scope.row.tags" :key="tag.tagId">{{tag.tagName}}</span>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col class="pagination">
                                <el-pagination :current-page="params.pageId" :page-size="params.pageSize" :total="count"
                                               @current-change="currentChange" background
                                               layout="total, prev, pager, next"/>
                            </el-col>
                        </el-row>
                    </template>
                    <template v-if="active === 3">
                        <el-row>
                            <el-form class="inline-form" inline>
                                <el-form-item>
                                    <el-button @click="toSelectUserPage"><i class="el-icon-arrow-left el-icon--left"/>上一步
                                    </el-button>
                                    <el-button @click="submit" :loading="submitting" type="primary"
                                               :disabled="selectNumber === 0 && !selectAllUser">提交
                                    </el-button>
                                </el-form-item>
                            </el-form>
                        </el-row>
                        <el-row>
                            <el-form class="inline-form">
                                <el-form-item label="当前模板">{{currentTemplate.title}}</el-form-item>
                                <el-form-item v-for="(label, key) in args" :key="key" :label="'参数(' + key + '): ' + label">
                                    {{values[key]}}
                                </el-form-item>
                                <template v-if="selectAllUser">
                                    <el-form-item label="用户范围">全部符合用户</el-form-item>
                                    <el-form-item label="已选择">{{count}}名用户</el-form-item>
                                    <el-form-item label="过滤条件"></el-form-item>
                                    <el-form-item v-if="params.openId" label="openId">{{params.openId}}</el-form-item>
                                    <el-form-item v-if="params.unionId" label="unionId">{{params.unionId}}</el-form-item>
                                    <el-form-item v-if="params.nickNameLike" label="昵称">{{params.nickNameLike}}</el-form-item>
                                    <el-form-item v-if="params.tagId" label="标签">
                                        <el-select disabled v-model="params.tagId">
                                            <el-option value="" label="不限"/>
                                            <el-option v-for="item in tags" :key="item.tagId"
                                                       :value="item.tagId" :label="item.tagName"/>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item v-if="params.activated !== ''" label="激活">{{params.activated ? '是' : '否'}}</el-form-item>
                                    <el-form-item v-if="registryTimes && registryTimes.length === 2" label="注册时间">
                                        <el-date-picker
                                                v-model="registryTimes"
                                                readonly
                                                type="datetimerange"
                                                range-separator="至"
                                                start-placeholder="开始时间"
                                                end-placeholder="结束时间"
                                                value-format="yyyy-MM-dd HH:mm:ss"
                                        />
                                    </el-form-item>
                                    <el-form-item v-if="lastLoginTimes && lastLoginTimes.length === 2" label="最后登录时间">
                                        <el-date-picker
                                                v-model="lastLoginTimes"
                                                readonly
                                                type="datetimerange"
                                                range-separator="至"
                                                start-placeholder="开始时间"
                                                end-placeholder="结束时间"
                                                value-format="yyyy-MM-dd HH:mm:ss"
                                        />
                                    </el-form-item>
                                </template>
                                <template v-else>
                                    <el-form-item label="用户范围">范围用户</el-form-item>
                                    <el-form-item label="已选择">{{selectNumber}}名用户</el-form-item>
                                    <el-form-item label="">
                                        <el-table :data="selectUsers" border size="small">
                                            <el-table-column align="center" label="openId" prop="openId"/>
                                            <el-table-column align="center" label="unionId" prop="unionId"/>
                                            <el-table-column align="center" label="昵称" prop="nickName"/>
                                            <el-table-column align="center" label="头像" width="80">
                                                <template slot-scope="scope">
                                                    <el-avatar shape="square" :src="scope.row.avatarUrl"/>
                                                </template>
                                            </el-table-column>
                                            <el-table-column align="center" label="注册时间" width="90">
                                                <template slot-scope="scope">
                                                    <p class="date-time">{{scope.row.registryTime | dateFormat}}</p>
                                                    <p class="date-time">{{scope.row.registryTime | timeFormat}}</p>
                                                </template>
                                            </el-table-column>
                                            <el-table-column align="center" label="最后登录时间" width="100">
                                                <template slot-scope="scope">
                                                    <p class="date-time">{{scope.row.lastLoginTime | dateFormat}}</p>
                                                    <p class="date-time">{{scope.row.lastLoginTime | timeFormat}}</p>
                                                </template>
                                            </el-table-column>
                                            <el-table-column align="center" label="激活用户" width="80">
                                                <template slot-scope="scope">
                                                    <commons-enable :value="scope.row.activated"/>
                                                </template>
                                            </el-table-column>
                                            <el-table-column align="center" label="标签">
                                                <template slot-scope="scope">
                                                    <span class="tag" v-for="tag in scope.row.tags" :key="tag.tagId">{{tag.tagName}}</span>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </el-form-item>
                                </template>
                            </el-form>
                        </el-row>
                    </template>
                    <template v-if="active === 4">
                        <el-row>
                            <el-button @click="init"><i class="el-icon-arrow-left el-icon--left"/>选择模板
                            </el-button>
                        </el-row>
                        <el-row>
                            <el-col>成功：{{successNumber}}, 失败: {{errors.length}}</el-col>
                        </el-row>
                        <el-row>
                            <el-table :data="errors" border size="small">
                                <el-table-column align="center" label="openId" prop="openId"/>
                                <el-table-column align="center" label="错误码" prop="errorCode"/>
                                <el-table-column align="center" label="错误信息" prop="errorMsg"/>
                            </el-table>
                        </el-row>
                    </template>
                </el-form>
            </el-row>
        </div>
    </el-row>
</template>
<script lang="ts">
import {PARAMS} from '@/api/http';
import FormRules from '@/structure/formRules';
import {ElForm} from 'element-ui/types/form';
import {ElTable} from 'element-ui/types/table';
import {Component, Vue} from 'vue-property-decorator';
import UserTagApi from '../../api/userTagApi';
import WxMaSubscribeMsgApi from '../../api/wxMaSubscribeMsgApi';
import WxUserApi from '../../api/wxUserApi';
import UserTag from '../../structure/userTag';
import WxMaSubscribeData from '../../structure/wxMaSubscribeData';
import WxMaSubscribeMessage from '../../structure/wxMaSubscribeMessage';
import WxMaSubscribeMsgTemplate from '../../structure/wxMaSubscribeMsgTemplate';
import WxMessageSendRequest from '../../structure/wxMessageSendRequest';
import Entity from '../../structure/wxUser';
import WxUser from '../../structure/wxUser';

interface ErrorInfo {
  openId: string;
  errorCode: number;
  errorMsg: string;
}

@Component
export default class Page extends Vue {
  public active: number = 0;
  public appId: string = '';
  public templates: WxMaSubscribeMsgTemplate[] = [];
  public currentTemplate: WxMaSubscribeMsgTemplate | '' = '';
  public selectedTemplate: boolean = false;
  public args: { [key: string]: string } = {};
  public values: { [key: string]: string } = {};
  public formRules: FormRules = {};
  public users: Entity[] = [];
  public tags: UserTag[] = [];
  public count: number | null = null;
  public params: PARAMS = {
    pageId: 1,
    openId: '',
    unionId: '',
    nickNameLike: null,
    activated: '',
    tagId: '',
    queryTags: true
  };
  public registryTimes: string[] = [];
  public lastLoginTimes: string[] = [];
  public selectUserMap: { [key: string]: WxUser | null } = {};
  public selectUsers: WxUser[] = [];
  public selectNumber: number = 0;
  public submitting: boolean = false;
  public errors: ErrorInfo[] = [];
  public successNumber: number = 0;
  public selectAllUser: boolean = false;

  public created(): void {
    this.appId = this.$route.params.appId;
    UserTagApi.all().then((res) => this.tags = res);
    WxMaSubscribeMsgApi.getList(this.appId).then((templates) => {
      templates.forEach((template) => {
        template.args = this.formatArgs(template);
      });
      this.templates = templates;
    });
  }

  public init() {
    this.currentTemplate = '';
    this.selectedTemplate = false;
    this.active = 0;
  }

  public formatArgs({content}: WxMaSubscribeMsgTemplate): { [key: string]: string } {
    return Object.fromEntries(content.split('\n').filter((e) => e)
      .map((e) => e.split(':'))
      .map((e) => [e[1].substring(2, e[1].length - 7), e[0]]));
  }

  public changeTemplate() {
    this.selectedTemplate = this.currentTemplate !== '';
    if (this.currentTemplate === '') {
      return;
    }

    this.args = this.currentTemplate.args;
    for (const key of Object.keys(this.args)) {
      this.formRules[key] = [
        {
          required: true,
          message: `请输入${this.args[key]}`
        }
      ];
    }
    this.active = 1;
  }

  public buildParams(): PARAMS {
    const params = {
      ...this.params,
      appId: this.appId,
      registryTimeStartWith: '',
      registryTimeEndWith: '',
      lastLoginTimeStartWith: '',
      lastLoginTimeEndWith: ''
    };

    if (this.registryTimes && this.registryTimes.length) {
      params.registryTimeStartWith = this.registryTimes[0];
      params.registryTimeEndWith = this.registryTimes[1];
    }
    if (this.lastLoginTimes && this.lastLoginTimes.length) {
      params.lastLoginTimeStartWith = this.lastLoginTimes[0];
      params.lastLoginTimeEndWith = this.lastLoginTimes[1];
    }

    return params;
  }

  public getDataList(): void {
    WxUserApi.findList(this.buildParams()).then((res) => {
      this.users = res.list;
      this.count = res.count;
      this.$nextTick(() => {
        const selected = {...this.selectUserMap};
        res.list.forEach((user) => {
          if (selected[user.openId]) {
            (this.$refs.userTable as ElTable).toggleRowSelection(user, true);
          }
        });
        this.setSelectNumber();
      });
    });
  }

  public toSelectUserPage() {
    const argForm = (this.$refs.argForm as ElForm);
    if (argForm) {
      argForm.validate((res) => {
        if (res) {
          this.active = 2;
          this.search();
        }
      });
    } else {
      this.active = 2;
      this.search();
    }
  }

  public search(): void {
    this.currentChange(1);
  }

  public currentChange(val: number): void {
    this.params.pageId = val;
    this.getDataList();
  }

  public selectUser(selects: WxUser[]) {
    this.users.forEach((user) => {
      this.selectUserMap[user.openId] = null;
    });
    selects.forEach((user) => {
      this.selectUserMap[user.openId] = user;
    });
    this.setSelectNumber();
  }

  public setSelectNumber() {
    this.selectNumber = Object.values(this.selectUserMap).filter((e) => e !== null).length;
  }

  public toConfirm(selectAllUser: boolean) {
    this.selectUsers = Object.values(this.selectUserMap).filter((e) => e !== null) as WxUser[];
    this.active = 3;
    this.selectAllUser = selectAllUser;
  }

  public submit() {
    if (this.submitting) {
      return;
    }
    this.submitting = true;

    const msgDataList: WxMaSubscribeData[] = [];
    Object.keys(this.args).forEach((key) => {
      msgDataList.push({
        name: key,
        value: this.values[key]
      });
    });

    const msg: WxMaSubscribeMessage = new WxMaSubscribeMessage();
    msg.data = msgDataList;
    msg.templateId = this.currentTemplate !== '' ? this.currentTemplate.priTmplId : '';

    const sendData: WxMessageSendRequest = new WxMessageSendRequest();
    if (this.selectAllUser) {
      sendData.selectAllUser = true;
      sendData.searchParams = this.buildParams();
    } else {
      sendData.openIds = Object.keys(this.selectUserMap).filter((openId) => this.selectUserMap[openId] !== null);
    }
    sendData.msg = msg;

    WxMaSubscribeMsgApi.sendMsg(this.appId, sendData).then((res) => {
      this.successNumber = 0;
      this.errors = [];
      Object.keys(res).forEach((openId) => {
        const {status, errorCode, errorMsg} = res[openId];
        if (status) {
          this.successNumber++;
        } else {
          this.errors.push({
            openId,
            errorCode,
            errorMsg
          });
        }
      });
      this.active = 4;
      this.submitting = false;
    }).catch(() => {
      this.submitting = false;
    });
  }
}
</script>
<style lang="scss" scoped>
    .tag {
        &:after {
            content: '、';
        }
        &:last-child:after {
            content: '';
        }
    }
</style>
